package com.xh.demo.common.interceptor;

import com.xh.demo.common.consts.ConfigConst;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Name FileUploadInterceptor
 * @Description 文件上传拦截器(判断文件是否超出制定大小,
 * 手动抛出MaxUploadSizeExceededException异常,有全局异常处理器处理
 * 此方法可解决MaxUploadSizeExceededException异常处理不了的情况,已弃用)
 * @Author wen
 * @Date 2019-08-02
 */
@Deprecated
public class FileUploadInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request != null && ServletFileUpload.isMultipartContent(request)) {
            ServletRequestContext ctx = new ServletRequestContext(request);
            long requestSize = ctx.contentLength();
            if (requestSize > ConfigConst.MAX_MAX_UPLOAD_SIZE_FILE) {
                throw new MaxUploadSizeExceededException(ConfigConst.MAX_MAX_UPLOAD_SIZE_FILE);
            }
        }
        return true;
    }
}
